﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JYH.Data;
using Newtonsoft.Json;
using JYH.Model;
using JYH.DataAccess;
using JYH.Framework;
using NetWorkLayer;
using System.Threading;
using JYH.Model.API;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using System.Timers;

namespace JYH.Business
{
    /// <summary>
    ///  WmsStockBarcode
    /// </summary>
    public class WmsStockBarcodeBLL : BusinessBase<WmsStockBarcode>
    {
        /// <summary>
        ///  WmsStockBarcode
        /// </summary>
        public WmsStockBarcodeBLL()
        {
            myDataBase = DB.D();
            this.SqlSelect = @"; Select WmsStockBarcode.*,BasBarcodeInfo.BarcodeNO,BasBarcodeInfo.BatchNO,
                                             BasMaterialInfo.MaterialNO,BasMaterialInfo.MaterialDesc,BasMaterialInfo.MaterialName,
                                             BasWarehouseInfo.WarehouseNO,BasWarehouseInfo.WarehouseName,BasLampInfo.LampNO,
                                             BasLampInfo.LampCode,BasRackInfo.RackNO,BasStorageInfo.StorageNO,
																						 BasPartnerInfo.PartnerName
                                             From WmsStockBarcode
                                             inner join BasBarcodeInfo on WmsStockBarcode.BarcodeID=BasBarcodeInfo.BarcodeID
                                             inner join BasMaterialInfo on WmsStockBarcode.MaterialID=BasMaterialInfo.MaterialID
                                             inner join BasWarehouseInfo on WmsStockBarcode.WarehouseID=BasWarehouseInfo.WarehouseID
                                             left join BasLampInfo on WmsStockBarcode.LampID=BasLampInfo.LampID
                                             left join BasRackInfo on BasLampInfo.RackID=BasRackInfo.RackID
											 left JOIN BasStorageInfo on BasStorageInfo.StorageID=WmsStockBarcode.StorageID
											 left JOIN BasPartnerInfo on BasBarcodeInfo.PartnerID=BasPartnerInfo.PartnerID";
        }

        /// <summary>
        /// 单据发料下架（批量）
        /// </summary>
        /// <param name="lists"></param>
        /// <param name="ligthCheck"></param>
        /// <param name="orderNO"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DBMaterialBarcode(ref List<WmsStockBarcode> info, bool ligthCheck, string OrderNO, ref ResponseJson<WmsStockBarcode> responseJson)
        {
            Sql sql = new Sql();
            StringBuilder sb = new StringBuilder();
            Database db = DB.D();
            db.BeginTransaction();
            bool falg = false;
            string BarCodes = "'',";
            try
            {
                WmsTradeOrderInfo TradeOrderInfo = new WmsTradeOrderInfo();
                WmsTradeSourceBLL tradeSourceBLL = new WmsTradeSourceBLL();
                WmsTradeSource TradeSourceList = new WmsTradeSource();
                WmsTradebarcodeBLL tradebarcodeBLL = new WmsTradebarcodeBLL();
                List<WmsTradebarcode> TradeBarcodeList = new List<WmsTradebarcode>();
                ///  单据号 不为空
                if (!string.IsNullOrWhiteSpace(OrderNO))
                {
                    sql = new Sql();
                    sql.Append("SELECT * FROM WmsTradeOrderInfo");
                    sql.Where($"WmsTradeOrderInfo.TradeOrderNO='{OrderNO}' ");
                    TradeOrderInfo = db.FirstOrDefault<WmsTradeOrderInfo>(sql);
                    if (TradeOrderInfo != null)
                    {
                        falg = true;
                        foreach (var item in info)
                        {
                            BarCodes += "'" + item.BarcodeNO + "',";
                        }
                        BarCodes = BarCodes.Substring(0, BarCodes.Length - 1);
                        sql = new Sql();
                        sql.Append(tradebarcodeBLL.SqlSelect);
                        sql.Where($"WmsTradeOrderInfo.TradeOrderNO='{OrderNO}' And WmsTradebarcode.RState=0");
                        sql.Where($"BasBarcodeInfo.BarcodeNO in ({BarCodes})");
                        TradeBarcodeList = db.Fetch<WmsTradebarcode>(sql);
                        if (!TradeBarcodeList.Any())
                        {
                            db.AbortTransaction();
                            responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("TradeOrderNoExist"), OrderNO);
                            return false;
                        }

                        sql = new Sql();
                        sql.Append(tradeSourceBLL.SqlSelect);
                        sql.Where($"WmsTradeOrderInfo.TradeOrderNO='{OrderNO}' ");
                        sql.Where($"WmsTradeSource.TradeSourceID = '{TradeBarcodeList[0].TradeSourceID}' ");
                        TradeSourceList = db.FirstOrDefault<WmsTradeSource>(sql);
                        if (TradeSourceList == null)
                        {
                            db.AbortTransaction();
                            responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("TradeOrderNoExist"), OrderNO);
                            return false;
                        }
                    }
                }

                #region 库存条码删除

                string CodeIDs = "";
                string TradeCodeID = "'',";
                decimal? StQty = 0;
                List<string> LampCodes = new List<string>();
                foreach (var item in TradeBarcodeList)
                {
                    if (!string.IsNullOrWhiteSpace(item.LampID))
                    {
                        LampCodes.Add(item.LampCode);
                    }
                    CodeIDs += "'" + item.BarcodeID + "',";
                    StQty += item.Qty;
                    TradeCodeID += "'" + item.TradebarcodeID + "',";
                }
                //回写来源单据号
                TradeSourceList.ActionQty += StQty;
                sb.Append(BusinessTool.GetUpdateSql(TradeSourceList));

                CodeIDs = CodeIDs.Substring(0, CodeIDs.Length - 1);
                //更新基础条码状态 IsStock=2
                sb.Append($"Update  BasBarcodeInfo  Set IsStock=2 where  BarcodeID  in ({CodeIDs})");

                TradeCodeID = TradeCodeID.Substring(0, TradeCodeID.Length - 1);
                //更新交易条码
                sb.Append($"Update  WmsTradebarcode  Set RState=1 where  TradebarcodeID  in ({TradeCodeID})");

                #endregion 库存条码删除

                #region 亮灯作业

                if (LampCodes.Count > 0)
                {
                    //绿灯
                    if (!NetWorkLayerHelper.OnLampCode((int)ColorCode.Green, LampCodes, true, false))
                    {
                        db.AbortTransaction();
                        responseJson.Message = ErrorCode.Admin.GetMessage();
                        return false;
                    }
                    foreach (var lampCode in LampCodes)
                    {
                        BasLampControl ctr = new BasLampControl();
                        ctr.LampControlID = Guid.NewGuid().ToString();
                        ctr.RState = "0";
                        ctr.NColor = 0;
                        ctr.LampNO = lampCode;
                        ctr.DoTime = DateTime.Now.AddMinutes(1).ToString("yyyy-MM-dd HH:mm:ss");
                        sb.Append(BusinessTool.GetInsertSql(ctr));
                    }
                }

                #endregion 亮灯作业

                if (sb.Length > 0)
                {
                    db.Execute(sb.ToString());
                }

                db.CompleteTransaction();
                return true;
            }
            catch (Exception ex)
            {
                db.AbortTransaction();
                responseJson.Message = ex.ToString();
                return false;
            }
        }

        /// <summary>
        /// 备料下架发料
        /// </summary>
        /// <param name="lists"></param>
        /// <param name="ligthCheck"></param>
        /// <param name="orderNO"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool MPMaterialBarcode(ref List<WmsTradebarcode> info, bool ligthCheck, string OrderNO, ref ResponseJson<WmsTradebarcode> responseJson)
        {
            Sql sql = new Sql();
            StringBuilder sb = new StringBuilder();
            Database db = DB.D();
            db.BeginTransaction();

            try
            {
                WmsTradeOrderInfo TradeOrderInfo = new WmsTradeOrderInfo();
                WmsTradeSourceBLL tradeSourceBLL = new WmsTradeSourceBLL();
                WmsTradebarcodeBLL tradebarcodeBLL = new WmsTradebarcodeBLL();
                List<WmsTradeSource> TradeSourceList = new List<WmsTradeSource>();
                ///  单据号 不为空
                if (!string.IsNullOrWhiteSpace(OrderNO))
                {
                    sql = new Sql();
                    sql.Append("SELECT * FROM WmsTradeOrderInfo");
                    sql.Where($"WmsTradeOrderInfo.TradeOrderNO='{OrderNO}'");
                    TradeOrderInfo = db.FirstOrDefault<WmsTradeOrderInfo>(sql);
                    if (TradeOrderInfo != null)
                    {
                        sql = new Sql();
                        sql.Append(tradeSourceBLL.SqlSelect);
                        sql.Where($"WmsTradeOrderInfo.TradeOrderNO='{OrderNO}'");
                        TradeSourceList = db.Fetch<WmsTradeSource>(sql);
                        if (!TradeSourceList.Any())
                        {
                            db.AbortTransaction();
                            responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("TradeOrderNoExist"), OrderNO);
                            return false;
                        }
                    }
                }

                #region 库存条码删除

                string IDs = "'',";
                string mIDs = "'',";
                string tradeIDs = "'',";
                foreach (var item in info)
                {
                    IDs += "'" + item.BarcodeNO + "',";
                    mIDs += "'" + item.BarcodeNO + "',";
                    tradeIDs += "'" + item.TradebarcodeID + "',";
                }
                tradeIDs = tradeIDs.Substring(0, tradeIDs.Length - 1);
                sql = new Sql();
                sql.Append(tradebarcodeBLL.SqlSelect);
                sql.Where($"WmsTradebarcode.TradebarcodeID in ({tradeIDs})");
                sql.OrderBy(" BasBarcodeInfo.BarcodeNO");
                var tradebarcodes = db.Fetch<WmsTradebarcode>(sql);
                if (!tradebarcodes.Any())
                {
                    db.AbortTransaction();
                    responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("StockNoExistBarcode"), info[0].BarcodeNO);
                    return false;
                }

                IDs = IDs.Substring(0, IDs.Length - 1);
                sql = new Sql();
                sql.Append(@";  Select WmsStockBarcode.*,WmsStockMaterial.StockMaterialID,BasLampInfo.LampNO,BasBarcodeInfo.BatchNO
                                From WmsStockBarcode
                                Inner JOin BasBarcodeInfo On BasBarcodeInfo.BarcodeID=WmsStockBarcode.BarcodeID
                                Inner JOin WmsStockMaterial On WmsStockBarcode.MaterialID=WmsStockMaterial.MaterialID
                                And WmsStockBarcode.WarehouseID=WmsStockMaterial.WarehouseID
                                And WmsStockBarcode.StorageID=WmsStockMaterial.StorageID
                                And BasBarcodeInfo.BatchNO=WmsStockMaterial.BatchNO
							    Left JOin BasLampInfo On WmsStockBarcode.LampID=BasLampInfo.LampID");
                sql.Where($"BasBarcodeInfo.BarcodeNO in ({IDs})");
                sql.OrderBy(" BasBarcodeInfo.BarcodeNO");
                var StockBarcodelist = db.Fetch<WmsStockBarcode>(sql);
                if (!StockBarcodelist.Any())
                {
                    db.AbortTransaction();
                    responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("StockNoExistBarcode"), info[0].BarcodeNO);
                    return false;
                }

                IDs = "'',";
                string LampNO = "";
                string CodeIDs = "";
                foreach (var item in StockBarcodelist)
                {
                    if (!string.IsNullOrWhiteSpace(item.LampID))
                    {
                        LampNO += "'" + item.LampNO + "',";
                    }
                    sb.Append(@"update WmsStockMaterial set   WmsStockMaterial.StockQty=WmsStockMaterial.StockQty-" + item.StockQty + " where StockMaterialID='" + item.StockMaterialID + "'");
                    IDs += "'" + item.StockBarcodeID + "',";
                    CodeIDs += "'" + item.BarcodeID + "',";
                }
                //回写来源明细
                //foreach (var tradeSource in TradeSourceList)
                //{
                //    // 查找 tradebarcodes 中 MaterialID、BatchNO、FromWarehouseID、StorageID 完全匹配的项
                //    var matchedItems = tradebarcodes.Where(t =>
                //        t.MaterialID == tradeSource.MaterialID &&
                //        t.StationNO == tradeSource.StationNO).ToList();

                //    if (matchedItems.Any())
                //    {
                //        // 累加 ActionQty
                //        tradeSource.ActionQty += matchedItems.Sum(t => t.Qty);

                //        // 可选：构建 SQL 更新语句
                //        sb.Append(BusinessTool.GetUpdateSql(tradeSource));
                //    }
                //}

                IDs = IDs.Substring(0, IDs.Length - 1);
                //更新库存条码状态 IsLock=1  在搜索的时候已经锁定了
                //sb.Append($"Update  WmsStockBarcode  Set IsLock=1 where  StockBarcodeID  in ({IDs})");

                //删除库存条码表
                sb.Append($"Delete from WmsStockBarcode where  StockBarcodeID  in ({IDs})");

                sb.Append($"Delete from WmsStockMaterial where  StockQty=0");
                CodeIDs = CodeIDs.Substring(0, CodeIDs.Length - 1);
                //更新基础条码状态 IsStock=0
                sb.Append($"Update  BasBarcodeInfo  Set IsStock=0 where  BarcodeID  in ({CodeIDs})");

                //更新tradebarcode
                sb.Append($"Update  WmsTradebarcode  Set RState=1 where  TradebarcodeID  in ({tradeIDs})");

                #endregion 库存条码删除

                #region 亮灯作业

                if (!string.IsNullOrWhiteSpace(LampNO))
                {
                    LampNO = LampNO.Substring(0, LampNO.Length - 1);
                    sql = new Sql();
                    sql.Append("SELECT * FROM BasLampInfo");
                    sql.Where($"BasLampInfo.LampNO in  ({LampNO})");
                    sql.OrderBy("BasLampInfo.LampNO");
                    var Lamps = db.Fetch<BasLampInfo>(sql);
                    sb.Append($"Update BasLampInfo Set RState='0' where BasLampInfo.LampNO  in ({LampNO}) ");
                    List<string> LampCodes = new List<string>();

                    foreach (var code in Lamps)
                    {
                        LampCodes.Add(code.LampCode);
                    }
                    //绿灯
                    if (!NetWorkLayerHelper.OnLampCode((int)ColorCode.Green, LampCodes, true, false))
                    {
                        db.AbortTransaction();
                        responseJson.Message = ErrorCode.Admin.GetMessage();
                        return false;
                    }
                    foreach (var lampCode in LampCodes)
                    {
                        BasLampControl ctr = new BasLampControl();
                        ctr.LampControlID = Guid.NewGuid().ToString();
                        ctr.RState = "0";
                        ctr.NColor = 0;
                        ctr.LampNO = lampCode;
                        ctr.DoTime = DateTime.Now.AddMinutes(1).ToString("yyyy-MM-dd HH:mm:ss");
                        sb.Append(BusinessTool.GetInsertSql(ctr));
                    }
                }

                #endregion 亮灯作业

                if (sb.Length > 0)
                {
                    db.Execute(sb.ToString());
                }

                db.CompleteTransaction();
                return true;
            }
            catch (Exception ex)
            {
                db.AbortTransaction();
                responseJson.Message = ex.ToString();
                return false;
            }
        }

        /// <summary>
        /// 批量无单下架
        /// </summary>
        /// <param name="info"></param>
        /// <param name="Ligth">是否亮灯</param>
        /// <param name="responseJson"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool OutMaterialBarcode(ref List<WmsStockBarcode> info, bool Ligth, ref ResponseJson<WmsStockBarcode> responseJson)
        {
            Sql sql = new Sql();
            StringBuilder sb = new StringBuilder();
            Database db = DB.D();
            db.BeginTransaction();

            try
            {
                WmsTradeOrderInfo TradeOrderInfo = new WmsTradeOrderInfo();
                WmsTradeSourceBLL tradeSourceBLL = new WmsTradeSourceBLL();
                List<WmsTradeSource> TradeSourceList = new List<WmsTradeSource>();

                #region 库存条码删除

                string IDs = "'',";
                string mIDs = "'',";
                foreach (var item in info)
                {
                    IDs += "'" + item.BarcodeNO + "',";
                    mIDs += "'" + item.BarcodeNO + "',";
                }
                IDs = IDs.Substring(0, IDs.Length - 1);
                sql = new Sql();
                sql.Append(@";  Select WmsStockBarcode.*,WmsStockMaterial.StockMaterialID,BasLampInfo.LampNO
                                From WmsStockBarcode
                                Inner JOin BasBarcodeInfo On BasBarcodeInfo.BarcodeID=WmsStockBarcode.BarcodeID
                                Inner JOin WmsStockMaterial On WmsStockBarcode.MaterialID=WmsStockMaterial.MaterialID
                                And WmsStockBarcode.WarehouseID=WmsStockMaterial.WarehouseID
                                And WmsStockBarcode.StorageID=WmsStockMaterial.StorageID
                                And BasBarcodeInfo.BatchNO=WmsStockMaterial.BatchNO
							    Left JOin BasLampInfo On WmsStockBarcode.LampID=BasLampInfo.LampID");
                sql.Where($"BasBarcodeInfo.BarcodeNO in ({IDs})");
                sql.OrderBy(" BasBarcodeInfo.BarcodeNO");
                var StockBarcodelist = db.Fetch<WmsStockBarcode>(sql);
                if (!StockBarcodelist.Any())
                {
                    db.AbortTransaction();
                    responseJson.Message = "Barcode is not in Stock";
                    return false;
                }

                IDs = "'',";
                string LampNO = "";

                foreach (var item in StockBarcodelist)
                {
                    if (!string.IsNullOrWhiteSpace(item.LampID))
                    {
                        LampNO += "'" + item.LampNO + "',";
                    }
                    sb.Append(@"update WmsStockMaterial set   WmsStockMaterial.StockQty=WmsStockMaterial.StockQty-" + item.StockQty + " where StockMaterialID='" + item.StockMaterialID + "'");
                    IDs += "'" + item.StockBarcodeID + "',";
                }
                IDs = IDs.Substring(0, IDs.Length - 1);
                //删除库存条码表
                sb.Append($"Delete from WmsStockBarcode where  StockBarcodeID  in ({IDs})");

                sb.Append($"Delete from WmsStockMaterial where  StockQty=0");

                //基础条码改变
                mIDs = mIDs.Substring(0, mIDs.Length - 1);
                sb.Append($"Update BasBarcodeInfo Set IsStock='0' where BasBarcodeInfo.BarcodeNO  in ({mIDs}) ");

                #endregion 库存条码删除

                #region 亮灯作业

                //灯珠
                if (!string.IsNullOrWhiteSpace(LampNO))
                {
                    LampNO = LampNO.Substring(0, LampNO.Length - 1);
                    sql = new Sql();
                    sql.Append("SELECT * FROM BasLampInfo");
                    sql.Where($"BasLampInfo.LampNO in  ({LampNO})");
                    sql.OrderBy("BasLampInfo.LampNO");
                    var Lamps = db.Fetch<BasLampInfo>(sql);
                    sb.Append($"Update BasLampInfo Set RState='0' where BasLampInfo.LampNO  in ({LampNO}) ");
                    List<string> LampCodes = new List<string>();

                    foreach (var code in Lamps)
                    {
                        LampCodes.Add(code.LampCode);
                    }
                    if (!NetWorkLayerHelper.OnLampCode((int)ColorCode.Green, LampCodes, true, false))
                    {
                        db.AbortTransaction();
                        responseJson.Message = ErrorCode.Admin.GetMessage();
                        return false;
                    }
                    foreach (var lampCode in LampCodes)
                    {
                        BasLampControl ctr = new BasLampControl();
                        ctr.LampControlID = Guid.NewGuid().ToString();
                        ctr.RState = "0";
                        ctr.NColor = 0;
                        ctr.LampNO = lampCode;
                        ctr.DoTime = DateTime.Now.AddMinutes(1).ToString("yyyy-MM-dd HH:mm:ss");
                        sb.Append(BusinessTool.GetInsertSql(ctr));
                    }
                }
                //库位
                //else
                //{
                //    sb.Append($"Update BasStorageInfo Set RState='0' where BasStorageInfo.StorageID  in ({StroIDs}) ");
                //}

                #endregion 亮灯作业

                if (sb.Length > 0)
                {
                    db.Execute(sb.ToString());
                }

                db.CompleteTransaction();
                return true;
            }
            catch (Exception ex)
            {
                db.AbortTransaction();
                responseJson.Message = ex.ToString();
                return false;
            }
        }

        /// <summary>
        /// 无单物料条码上架
        /// </summary>
        /// <param name="info">上架信息</param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public bool PutOnMaterialBarcode(ref WmsStockBarcode info, ref ResponseJson<WmsStockBarcode> responseJson)
        {
            Sql sql = new Sql();
            StringBuilder sb = new StringBuilder();
            Database db = DB.D();
            db.BeginTransaction();
            try
            {
                BasLampInfo lamp = new BasLampInfo();
                BasStorageInfo storage = new BasStorageInfo();
                sql = new Sql();
                sql.Append(";Select * From BasBarcodeInfo");
                sql.Where("BasBarcodeInfo.BarcodeNO='" + info.BarcodeNO + "'");
                BasBarcodeInfo barcodeInfo = new BasBarcodeInfo();
                barcodeInfo = db.FirstOrDefault<BasBarcodeInfo>(sql);

                sql = new Sql();
                sql.Append(";Select BasWarehouseInfo.* From BasWarehouseInfo");
                sql.Where("BasWarehouseInfo.WarehouseID='" + info.WarehouseID + "' or BasWarehouseInfo.WarehouseNO='" + info.WarehouseID + "' ");
                BasWarehouseInfo warehouseInfo = new BasWarehouseInfo();
                warehouseInfo = db.FirstOrDefault<BasWarehouseInfo>(sql);
                if (warehouseInfo == null)
                {
                    responseJson.Message = "Warehouse Is not Exiten";
                    // responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("WarehouseInfo01"), info.WarehouseID);
                    db.AbortTransaction();
                    return false;
                }
                if (barcodeInfo == null)
                {
                    responseJson.Message = "Barcode Is not Exiten";
                    //responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistBaercode"), info.BarcodeNO);
                    db.AbortTransaction();
                    return false;
                }

                ///在库
                if (barcodeInfo.IsStock >= 1)
                {
                    responseJson.Message = "Barcode Is Already In Stock";
                    // responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("BarcodeInfo01"), barcodeInfo.BarcodeNO);
                    db.AbortTransaction();
                    return false;
                }
                // -1  表示库位模式  >=0  表示灯珠模式
                if (info.ShelfOption == "-1")
                {
                    sql = new Sql();
                    sql.Append(";Select * From BasStorageInfo");
                    sql.Where("BasStorageInfo.StorageNO='" + info.ListingNO.Trim() + "'");
                    storage = db.FirstOrDefault<BasStorageInfo>(sql);
                    if (storage == null)
                    {
                        responseJson.Message = "Storage Is Not Existence ";
                        // responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistStorage"), info.StorageNO);
                        db.AbortTransaction();
                        return false;
                    }
                    if (!string.Equals(warehouseInfo.WarehouseID, storage.WarehouseID))
                    {
                        responseJson.Message = "The storage location does not match the warehouse.";
                        //responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("WarehouseInfo02"), storage.StorageNO, warehouseInfo.WarehouseNO);
                        db.AbortTransaction();
                        return false;
                    }
                }
                else
                {
                    sql = new Sql();
                    sql.Append(";Select * From BasStorageInfo");
                    sql.Where("BasStorageInfo.WarehouseID='" + warehouseInfo.WarehouseID + "'");
                    sql.OrderBy("BasStorageInfo.StorageNO");
                    var storages = db.Fetch<BasStorageInfo>(sql);
                    if (storages == null || storages.Count < 1)
                    {
                        responseJson.Message = "Storage Is Not Existence ";
                        // responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("WarehouseInfo03"), storage.StorageNO, warehouseInfo.WarehouseNO);
                        db.AbortTransaction();
                        return false;
                    }

                    storage = storages[0];
                    sql = new Sql();
                    sql.Append(";Select * From BasLampInfo");
                    sql.Where("BasLampInfo.LampNO='" + info.ListingNO.Trim() + "' And BasLampInfo.RState=0");

                    lamp = db.FirstOrDefault<BasLampInfo>(sql);
                    if (lamp == null)
                    {
                        responseJson.Message = " LampNO is not Existence";
                        // responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistLamp"), info.LampNO);
                        db.AbortTransaction();
                        return false;
                    }
                    lamp.RState = "1";
                    sb.Append(BusinessTool.GetUpdateSql(lamp));
                }
                sql = new Sql();
                sql.Append(@";Select WmsStockBarcode.*,BasBarcodeInfo.BatchNO from WmsStockBarcode
                              Inner JOin BasBarcodeInfo ON WmsStockBarcode.BarcodeID=BasBarcodeInfo.BarcodeID");
                sql.Where("BasBarcodeInfo.BarcodeNO='" + info.BarcodeNO + "'");
                WmsStockBarcode StockBarcode = new WmsStockBarcode();
                StockBarcode = db.FirstOrDefault<WmsStockBarcode>(sql);
                if (StockBarcode != null)
                {
                    responseJson.Message = "Barcode Is Already In Stock";
                    //   responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("StockExistBarcode"), info.BarcodeNO);
                    return false;
                }
                StockBarcode = new WmsStockBarcode();
                StockBarcode.BarcodeID = barcodeInfo.BarcodeID;
                StockBarcode.StockBarcodeID = Guid.NewGuid().ToString();
                StockBarcode.StockQty = barcodeInfo.Qty;
                if (storage != null)
                {
                    StockBarcode.StorageID = storage.StorageID;
                }

                StockBarcode.LampID = lamp.LampID;
                StockBarcode.MaterialID = barcodeInfo.MaterialID;
                StockBarcode.WarehouseID = warehouseInfo.WarehouseID;
                StockBarcode.CreateUser = info.UserName;
                sb.Append(BusinessTool.GetInsertSql(StockBarcode));
                WmsStockMaterial StockMaterial = new WmsStockMaterial();
                sql = new Sql();
                sql.Append("Select * from WmsStockMaterial");
                sql.Where("WmsStockMaterial.MaterialID='" + barcodeInfo.MaterialID + "'");
                sql.Where("WmsStockMaterial.WarehouseID='" + warehouseInfo.WarehouseID + "'");
                if (storage != null)
                    sql.Where("WmsStockMaterial.StorageID='" + storage.StorageID + "'");
                sql.Where("WmsStockMaterial.BatchNO='" + barcodeInfo.BatchNO + "'");
                StockMaterial = db.FirstOrDefault<WmsStockMaterial>(sql);
                if (StockMaterial == null)
                {
                    StockMaterial = new WmsStockMaterial();
                    StockMaterial.StockMaterialID = Guid.NewGuid().ToString();
                    StockMaterial.MaterialID = barcodeInfo.MaterialID;

                    if (storage != null)
                    {
                        StockMaterial.StorageID = storage.StorageID;
                    }

                    StockMaterial.WarehouseID = warehouseInfo.WarehouseID;
                    StockMaterial.BatchNO = barcodeInfo.BatchNO;
                    StockMaterial.StockQty = barcodeInfo.Qty;
                    StockMaterial.CreateUser = info.UserName;
                    StockMaterial.TradeDate = DateTime.Now.ToString("yyyy-MM-dd");
                    sb.Append(BusinessTool.GetInsertSql(StockMaterial));
                }
                else
                {
                    StockMaterial.StockQty += barcodeInfo.Qty;
                    StockMaterial.UpdateUser = info.UserName;
                    StockMaterial.TradeDate = DateTime.Now.ToString("yyyy-MM-dd");
                    sb.Append(BusinessTool.GetUpdateSql(StockMaterial));
                }

                string NewLampNO = "";
                List<BasLampInfo> Lamps = new List<BasLampInfo>();
                if (info.ShelfOption != "-1")
                {
                    // NetWorkLayerHelper.InitComNetClient();
                    if (info.ShelfOption == "0")
                    {
                        sql = new Sql();
                        sql.Append("SELECT top 2  BasLampInfo.LampNO,BasLampInfo.LampCode FROM BasLampInfo");
                        sql.Where($"BasLampInfo.RackID = '{lamp.RackID}'");
                        sql.Where($"BasLampInfo.LampNO >= '{lamp.LampNO}'");
                        sql.Where($"BasLampInfo.RState ='0'");
                        sql.OrderBy("BasLampInfo.LampNO");
                        Lamps = db.Fetch<BasLampInfo>(sql);
                        if (Lamps.Count == 2)
                        {
                            //下个灯珠亮灯
                            List<string> LampCodes = new List<string>();
                            LampCodes.Add(Lamps[1].LampCode);
                            NewLampNO = Lamps[1].LampCode;
                            //NetWorkLayerHelper.MutiShelfLEDBatchControl(0, LampCodes, false, false);
                            Thread.Sleep(500);
                            //等待作业，显示黄色
                            if (!NetWorkLayerHelper.OnLampCode((int)ColorCode.Yellow, LampCodes, true, false))
                            {
                                db.AbortTransaction();
                                responseJson.Message = ErrorCode.Admin.GetMessage();
                                return false;
                            }
                            BasLampControl ctr = new BasLampControl();
                            ctr.LampControlID = Guid.NewGuid().ToString();
                            ctr.RState = "0";
                            ctr.NColor = 0;
                            ctr.LampNO = Lamps[1].LampCode;
                            ctr.DoTime = DateTime.Now.AddMinutes(1).ToString("yyyy-MM-dd HH:mm:ss");
                            sb.Append(BusinessTool.GetInsertSql(ctr));

                            LampCodes = new List<string>();
                            LampCodes.Add(Lamps[0].LampCode);
                            //NetWorkLayerHelper.MutiShelfLEDBatchControl(0, LampCodes, false, false);
                            //Thread.Sleep(500);
                            //作业完成，显示绿色
                            if (!NetWorkLayerHelper.OnLampCode((int)ColorCode.Green, LampCodes, true, false))
                            {
                                db.AbortTransaction();
                                responseJson.Message = ErrorCode.Admin.GetMessage();
                                return false;
                            }
                            //当前灯珠
                            ctr = new BasLampControl();
                            ctr.LampControlID = Guid.NewGuid().ToString();
                            ctr.RState = "0";
                            ctr.NColor = 0;
                            ctr.LampNO = Lamps[0].LampCode;
                            ctr.DoTime = DateTime.Now.AddSeconds(5).ToString("yyyy-MM-dd HH:mm:ss");
                            sb.Append(BusinessTool.GetInsertSql(ctr));
                        }
                    }
                    else
                    {
                        sql = new Sql();
                        sql.Append("SELECT top 1  BasLampInfo.LampNO,BasLampInfo.LampCode FROM BasLampInfo");
                        sql.Where($"BasLampInfo.RackID = '{lamp.RackID}'");
                        sql.Where($"BasLampInfo.LampNO = '{lamp.LampNO}'");
                        sql.Where($"BasLampInfo.RState = '0'");
                        sql.OrderBy("BasLampInfo.LampNO");
                        Lamps = db.Fetch<BasLampInfo>(sql);
                        if (Lamps.Count == 1)
                        {
                            List<string> LampCodes = new List<string>();
                            LampCodes.Add(Lamps[0].LampCode);
                            //当前灯珠
                            BasLampControl ctr = new BasLampControl();
                            ctr.LampControlID = Guid.NewGuid().ToString();
                            ctr.RState = "0";
                            ctr.NColor = 0;
                            ctr.LampNO = Lamps[0].LampCode;
                            ctr.DoTime = DateTime.Now.AddSeconds(5).ToString("yyyy-MM-dd HH:mm:ss");
                            sb.Append(BusinessTool.GetInsertSql(ctr));
                            //NetWorkLayerHelper.MutiShelfLEDBatchControl(0, LampCodes, false, false);

                            //Thread.Sleep(1000);
                            //作业完成，显示绿色
                            if (!NetWorkLayerHelper.OnLampCode((int)ColorCode.Green, LampCodes, true, false))
                            {
                                db.AbortTransaction();
                                responseJson.Message = ErrorCode.Admin.GetMessage();
                                return false;
                            }
                        }
                    }

                    //顺序上架
                }
                //赋值
                info.LampNO = NewLampNO;

                //修改状态值
                barcodeInfo.IsStock = 1;

                sb.Append(BusinessTool.GetUpdateSql(barcodeInfo));
                if (sb.Length > 0)
                {
                    db.Execute(sb.ToString());
                }

                db.CompleteTransaction();
                return true;
            }
            catch (Exception ex)
            {
                db.AbortTransaction();
                responseJson.Message = ex.ToString();
                return false;
            }
        }

        /// <summary>
        /// 调拨条码上架
        /// </summary>
        /// <param name="info">上架信息</param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public bool TradePutOnBarcode_5(ref WmsTradebarcode info, ref ResponseJson<WmsTradebarcode> responseJson)
        {
            Sql sql = new Sql();
            StringBuilder sb = new StringBuilder();
            Database db = DB.D();
            db.BeginTransaction();
            try
            {
                WmsTradebarcodeBLL tradebarcodeBLL = new WmsTradebarcodeBLL();
                sql = new Sql();
                sql.Append(tradebarcodeBLL.SqlSelect);
                sql.Where($"WmsTradeOrderInfo.TradeOrderNO='{info.TradeOrderNO}'");
                sql.Where($"BasBarcodeInfo.BarcodeNO='{info.BarcodeNO}' And WmsTradebarcode.RState=2");
                var tradebarcodelist = db.FirstOrDefault<WmsTradebarcode>(sql);
                if (tradebarcodelist == null)
                {
                    responseJson.Message = info.BarcodeNO + " is Sing in";
                    // responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("WarehouseInfo01"), info.WarehouseID);
                    db.AbortTransaction();
                    return false;
                }

                sql = new Sql();
                sql.Append(@";  Select WmsStockBarcode.*,WmsStockMaterial.StockMaterialID,BasLampInfo.LampNO,BasBarcodeInfo.BatchNO
                                From WmsStockBarcode
                                Inner JOin BasBarcodeInfo On BasBarcodeInfo.BarcodeID=WmsStockBarcode.BarcodeID
                                Inner JOin WmsStockMaterial On WmsStockBarcode.MaterialID=WmsStockMaterial.MaterialID
                                And WmsStockBarcode.WarehouseID=WmsStockMaterial.WarehouseID
                                And WmsStockBarcode.StorageID=WmsStockMaterial.StorageID
                                And BasBarcodeInfo.BatchNO=WmsStockMaterial.BatchNO
							    Left JOin BasLampInfo On WmsStockBarcode.LampID=BasLampInfo.LampID");
                sql.Where($"BasBarcodeInfo.BarcodeNO ='{info.BarcodeNO}'");
                sql.Where($"WmsStockBarcode.WarehouseID='{info.WarehouseID}'");
                sql.OrderBy(" BasBarcodeInfo.BarcodeNO");
                var StockBarcodelist = db.Fetch<WmsStockBarcode>(sql);
                if (StockBarcodelist.Any())
                {
                    db.AbortTransaction();
                    responseJson.Message = info.BarcodeNO + " is Sing in";
                    return false;
                }

                BasStorageInfo storage = new BasStorageInfo();
                BasLampInfo lamp = new BasLampInfo();
                BasStorageInfoBLL storageInfoBLL = new BasStorageInfoBLL();
                // -1  表示库位模式  >=0  表示灯珠模式
                if (string.IsNullOrEmpty(info.LampNO))
                {
                    sql = new Sql();
                    sql.Append(storageInfoBLL.SqlSelect);
                    sql.Where("BasStorageInfo.StorageNO='" + info.StorageNO + "' And BasWarehouseInfo.WarehouseID='" + info.WarehouseID + "'");
                    storage = db.FirstOrDefault<BasStorageInfo>(sql);
                    if (storage == null)
                    {
                        responseJson.Message = "Storage Is Not Existence ";
                        // responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistStorage"), info.StorageNO);
                        db.AbortTransaction();
                        return false;
                    }
                }
                else
                {
                    sql = new Sql();
                    sql.Append(storageInfoBLL.SqlSelect);
                    sql.Where("BasStorageInfo.StorageNO='" + info.StorageNO + "' And BasWarehouseInfo.WarehouseID='" + info.WarehouseID + "'");
                    storage = db.FirstOrDefault<BasStorageInfo>(sql);
                    if (storage == null)
                    {
                        responseJson.Message = "Storage Is Not Existence ";
                        // responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistStorage"), info.StorageNO);
                        db.AbortTransaction();
                        return false;
                    }
                    sql = new Sql();
                    sql.Append(";Select * From BasLampInfo");
                    sql.Where("BasLampInfo.LampNO='" + info.LampNO + "' And BasLampInfo.RState=0");

                    lamp = db.FirstOrDefault<BasLampInfo>(sql);
                    if (lamp == null)
                    {
                        responseJson.Message = " LampNO is not Existence";
                        // responseJson.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistLamp"), info.LampNO);
                        db.AbortTransaction();
                        return false;
                    }
                    lamp.RState = "1";
                    sb.Append(BusinessTool.GetUpdateSql(lamp));
                }
                var UserName = info.UserName;
                WmsStockBarcode StockBarcode = new WmsStockBarcode();
                StockBarcode = new WmsStockBarcode();
                StockBarcode.BarcodeID = tradebarcodelist.BarcodeID;
                StockBarcode.StockBarcodeID = Guid.NewGuid().ToString();
                StockBarcode.StockQty = tradebarcodelist.Qty;
                if (storage != null)
                {
                    StockBarcode.StorageID = storage.StorageID;
                }
                StockBarcode.LampID = lamp.LampID;
                StockBarcode.MaterialID = tradebarcodelist.MaterialID;
                StockBarcode.WarehouseID = storage.WarehouseID;
                StockBarcode.CreateUser = UserName;
                StockBarcode.BatchNO = tradebarcodelist.BatchNO;
                sb.Append(BusinessTool.GetInsertSql(StockBarcode));

                WmsStockMaterial StockMaterial = new WmsStockMaterial();
                sql = new Sql();
                sql.Append("Select * from WmsStockMaterial");
                sql.Where("WmsStockMaterial.MaterialID='" + tradebarcodelist.MaterialID + "'");
                sql.Where("WmsStockMaterial.WarehouseID='" + storage.WarehouseID + "'");
                if (storage != null)
                    sql.Where("WmsStockMaterial.StorageID='" + storage.StorageID + "'");
                sql.Where("WmsStockMaterial.BatchNO='" + tradebarcodelist.BatchNO + "'");
                StockMaterial = db.FirstOrDefault<WmsStockMaterial>(sql);
                if (StockMaterial == null)
                {
                    StockMaterial = new WmsStockMaterial();
                    StockMaterial.StockMaterialID = Guid.NewGuid().ToString();
                    StockMaterial.MaterialID = StockBarcode.MaterialID;

                    if (storage != null)
                    {
                        StockMaterial.StorageID = StockBarcode.StorageID;
                    }

                    StockMaterial.WarehouseID = StockBarcode.WarehouseID;
                    StockMaterial.BatchNO = StockBarcode.BatchNO;
                    StockMaterial.StockQty = StockBarcode.StockQty;
                    StockMaterial.CreateUser = UserName;
                    StockMaterial.TradeDate = DateTime.Now.ToString("yyyy-MM-dd");
                    sb.Append(BusinessTool.GetInsertSql(StockMaterial));
                }
                else
                {
                    StockMaterial.StockQty += StockBarcode.StockQty;
                    StockMaterial.UpdateUser = UserName;
                    StockMaterial.TradeDate = DateTime.Now.ToString("yyyy-MM-dd");
                    sb.Append(BusinessTool.GetUpdateSql(StockMaterial));
                }

                string NewLampNO = "";

                string ToLampNO = "";
                List<BasLampInfo> Lamps = new List<BasLampInfo>();

                // NetWorkLayerHelper.InitComNetClient();
                if (!string.IsNullOrEmpty(info.LampNO))
                {
                    sql = new Sql();
                    sql.Append("SELECT top 2  BasLampInfo.LampNO,BasLampInfo.LampCode FROM BasLampInfo");
                    sql.Where($"BasLampInfo.RackID = '{lamp.RackID}'");
                    sql.Where($"BasLampInfo.LampNO >= '{lamp.LampNO}'");
                    sql.Where($"BasLampInfo.RState ='0'");
                    sql.OrderBy("BasLampInfo.LampNO");
                    Lamps = db.Fetch<BasLampInfo>(sql);
                    if (Lamps.Count == 2)
                    {
                        //下个灯珠亮灯
                        List<string> LampCodes = new List<string>();
                        LampCodes.Add(Lamps[1].LampCode);
                        NewLampNO = Lamps[1].LampCode;

                        //等待作业，显示黄色
                        if (!NetWorkLayerHelper.OnLampCode((int)ColorCode.Yellow, LampCodes, true, false))
                        {
                            db.AbortTransaction();
                            responseJson.Message = ErrorCode.Admin.GetMessage();
                            return false;
                        }
                        BasLampControl ctr = new BasLampControl();
                        ctr.LampControlID = Guid.NewGuid().ToString();
                        ctr.RState = "0";
                        ctr.NColor = 0;
                        ctr.LampNO = Lamps[1].LampCode;
                        ctr.DoTime = DateTime.Now.AddMinutes(1).ToString("yyyy-MM-dd HH:mm:ss");
                        sb.Append(BusinessTool.GetInsertSql(ctr));

                        LampCodes = new List<string>();
                        LampCodes.Add(Lamps[0].LampCode);
                        ToLampNO = Lamps[0].LampNO;
                        //作业完成，显示绿色
                        if (!NetWorkLayerHelper.OnLampCode((int)ColorCode.Green, LampCodes, true, false))
                        {
                            db.AbortTransaction();
                            responseJson.Message = ErrorCode.Admin.GetMessage();
                            return false;
                        }
                        //当前灯珠
                        ctr = new BasLampControl();
                        ctr.LampControlID = Guid.NewGuid().ToString();
                        ctr.RState = "0";
                        ctr.NColor = 0;
                        ctr.LampNO = Lamps[0].LampCode;
                        ctr.DoTime = DateTime.Now.AddSeconds(5).ToString("yyyy-MM-dd HH:mm:ss");
                        sb.Append(BusinessTool.GetInsertSql(ctr));
                    }
                }

                //赋值

                tradebarcodelist.ToLampNO = ToLampNO;
                tradebarcodelist.ToLampID = lamp.LampID;
                tradebarcodelist.ToStorageNO = storage.StorageNO;
                tradebarcodelist.ToStorageID = storage.StorageID;
                //修改状态值
                tradebarcodelist.RState = "3";
                sb.Append(BusinessTool.GetUpdateSql(tradebarcodelist));
                tradebarcodelist.LampNO = NewLampNO;
                if (sb.Length > 0)
                {
                    db.Execute(sb.ToString());
                }
                responseJson.Items.Add(tradebarcodelist);
                db.CompleteTransaction();
                return true;
            }
            catch (Exception ex)
            {
                db.AbortTransaction();
                responseJson.Message = ex.ToString();
                return false;
            }
        }

        /// <summary>
        ///  捡料下架-检索物料
        /// </summary>
        /// <param name="info">需求对象 有物料编号，需求总数,仓库IDMaterialNO,Qty,WarehouseID</param>
        /// <param name="BatchNO">物料批号</param>
        /// <param name="json">返回消息</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool GetStockBarCodeInfo(BasBarcodeInfo info, ref ResponseJson<WmsStockBarcode> json, string BatchNO = null, string StrongNO = null, string BarCodeNO = null)
        {
            StringBuilder sb = new StringBuilder();
            Sql sql = new Sql();
            string Msg = string.Empty;
            try
            {
                //库存条码信息  只查询有实物的灯珠
                sql.Append(this.SqlSelect);
                if (!string.IsNullOrWhiteSpace(BatchNO))
                {
                    sql.Where($"BasBarcodeInfo.BatchNO='{BatchNO}'");
                }
                if (!string.IsNullOrWhiteSpace(StrongNO))
                {
                    sql.Where($"BasBarcodeInfo.BatchNO='{StrongNO}'");
                }
                if (info != null)
                {
                    sql.Where($"WmsStockBarcode.MaterialID = (SELECT MaterialID FROM BasMaterialInfo WHERE MaterialNO = '{info.MaterialNO}')");
                    sql.Where($"WmsStockBarcode.WarehouseID = '{info.WarehouseID}'");
                }
                if (!string.IsNullOrWhiteSpace(BarCodeNO))
                {
                    sql.Where($"BasBarcodeInfo.BarcodeNO='{BarCodeNO}'");
                }
                sql.Where("WmsStockBarcode.IsLock=0 And BasBarcodeInfo.IsStock=1");
                sql.OrderBy("BasBarcodeInfo.BatchNO ASC");
                sql.OrderBy("WmsStockBarcode.StockQty ASC");
                List<WmsStockBarcode> allBarcodes = myDataBase.Fetch<WmsStockBarcode>(sql);
                if (!allBarcodes.Any())
                {
                    json.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistBaercode"), info != null ? info.BarcodeNO : BarCodeNO);
                    return false;
                }
                string IDs = "";
                // 2. 累加数量，找出满足 info.Qty 的最小集合
                decimal? totalSelectedQty = 0;
                List<WmsStockBarcode> selectedBarcodes = new List<WmsStockBarcode>();
                if (!string.IsNullOrWhiteSpace(BarCodeNO))
                {
                    selectedBarcodes = allBarcodes;
                    IDs = "'" + allBarcodes[0].BarcodeID + "',";
                }
                else
                {
                    foreach (var barcode in allBarcodes)
                    {
                        IDs += "'" + barcode.BarcodeID + "',";
                        selectedBarcodes.Add(barcode);
                        totalSelectedQty += barcode.StockQty;
                        if (totalSelectedQty >= info.Qty)
                            break;
                    }
                    IDs = IDs.Substring(0, IDs.Length - 1);
                    myDataBase.Execute($"Update WmsStockBarcode Set IsLock=1 where WmsStockBarcode.BarcodeID in ({IDs})");
                }

                // 3. 设置返回结果
                json.Items = selectedBarcodes;
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 库存集合亮灯
        /// </summary>
        /// <param name="info"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public void QueryLigthInfo(LigthList<WmsStockBarcode> info, ref ResponseJson<WmsStockBarcode> json)
        {
            try
            {
                List<string> LampCodes = new List<string>();
                foreach (var code in info.Items)
                {
                    LampCodes.Add(code.LampCode);
                }
                if (!NetWorkLayerHelper.OnLampCode((int)info.Color, LampCodes, info.LigthCheck, false))
                {
                    json.Message = ErrorCode.Admin.GetMessage();
                }
            }
            catch (Exception ex)
            {
                json.Code = 500;
                json.Message = ex.Message;
            }
        }

        /// <summary>
        /// 库存码查询
        /// </summary>
        /// <param name="info"></param>
        /// <param name="json"></param>
        /// <param name="BatchNO"></param>
        /// <param name="StrongNO"></param>
        /// <param name="BarCodeNO"></param>
        /// <returns></returns>
        public bool GetStockCodeList(BasBarcodeInfo info, ref ResponseJson<WmsStockBarcode> json, string BatchNO = null, string StrongNO = null, string BarCodeNO = null)
        {
            StringBuilder sb = new StringBuilder();
            Sql sql = new Sql();
            string Msg = string.Empty;
            try
            {
                //库存条码信息  只查询有实物的灯珠
                sql.Append(this.SqlSelect);
                if (!string.IsNullOrWhiteSpace(BatchNO))
                {
                    sql.Where($"BasBarcodeInfo.BatchNO='{BatchNO}'");
                }
                if (!string.IsNullOrWhiteSpace(StrongNO))
                {
                    sql.Where($"BasBarcodeInfo.BatchNO='{StrongNO}'");
                }
                if (info != null)
                {
                    sql.Where($"WmsStockBarcode.MaterialID = (SELECT MaterialID FROM BasMaterialInfo WHERE MaterialNO = '{info.MaterialNO}')");
                    sql.Where($"WmsStockBarcode.WarehouseID = '{info.WarehouseID}'");
                }
                if (!string.IsNullOrWhiteSpace(BarCodeNO))
                {
                    sql.Where($"BasBarcodeInfo.BarcodeNO='{BarCodeNO}'");
                }
                sql.Where("BasBarcodeInfo.IsStock=1");
                sql.OrderBy("BasBarcodeInfo.BatchNO ASC");
                sql.OrderBy("WmsStockBarcode.StockQty ASC");
                List<WmsStockBarcode> allBarcodes = myDataBase.Fetch<WmsStockBarcode>(sql);
                if (!allBarcodes.Any())
                {
                    json.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistBaercode"), info != null ? info.BarcodeNO : BarCodeNO);
                    return false;
                }
                string IDs = "";
                // 2. 累加数量，找出满足 info.Qty 的最小集合
                decimal? totalSelectedQty = 0;
                List<WmsStockBarcode> selectedBarcodes = new List<WmsStockBarcode>();
                if (!string.IsNullOrWhiteSpace(BarCodeNO))
                {
                    selectedBarcodes = allBarcodes;
                    IDs = "'" + allBarcodes[0].BarcodeID + "',";
                }
                else
                {
                    foreach (var barcode in allBarcodes)
                    {
                        IDs += "'" + barcode.BarcodeID + "',";
                        selectedBarcodes.Add(barcode);
                        totalSelectedQty += barcode.StockQty;
                        if (totalSelectedQty >= info.Qty)
                            break;
                    }
                }
                //IDs = IDs.Substring(0, IDs.Length - 1);
                //myDataBase.Execute($"Update WmsStockBarcode Set IsLock=1 where WmsStockBarcode.BarcodeID in ({IDs})");
                // 3. 设置返回结果
                json.Items = selectedBarcodes;
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 解除库存锁定
        /// </summary>
        /// <param name="info"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool RelieveIsLock(List<WmsStockBarcode> info, ref ResponseJson<WmsStockBarcode> message)
        {
            Database db = DB.D();
            db.BeginTransaction();
            StringBuilder sb = new StringBuilder();
            Sql sql = new Sql();
            string Msg = string.Empty;
            try
            {
                string IDs = "";
                if (info.Count > 0)
                {
                    foreach (var barcode in info)
                    {
                        IDs += "'" + barcode.StockBarcodeID + "',";
                    }
                }
                if (!string.IsNullOrWhiteSpace(IDs))
                {
                    IDs = IDs.Substring(0, IDs.Length - 1);
                    db.Execute($"UPDATE WmsStockBarcode Set IsLock=0 where WmsStockBarcode.StockBarcodeID in ({IDs})");
                }
            }
            catch (Exception ex)
            {
                message.Message = ex.Message;
                db.AbortTransaction();
                return false;
            }
            db.CompleteTransaction();
            return true;
        }

        /// <summary>
        /// 调拨捡料
        /// </summary>
        /// <param name="info"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool GetCalculateInfo(WmsTradeSource info, ref ResponseJson<WmsTradebarcode> json, string BatchNO = null, string StrongNO = null, string FromWarehouseID = null, string BarCodeNO = null)
        {
            StringBuilder sb = new StringBuilder();
            Sql sql = new Sql();
            string Msg = string.Empty;
            Database db = DB.D();
            db.BeginTransaction();
            WmsTradeSourceBLL tradeSourceBLL = new WmsTradeSourceBLL();
            WmsTradeSource TradeSourceList = new WmsTradeSource();
            try
            {
                sql = new Sql();
                sql.Append(tradeSourceBLL.SqlSelect);
                sql.Where($"WmsTradeOrderInfo.TradeOrderNO='{info.TradeOrderNO}' ");
                sql.Where($"WmsTradeSource.TradeSourceID = '{info.TradeSourceID}' ");
                TradeSourceList = db.FirstOrDefault<WmsTradeSource>(sql);
                if (TradeSourceList == null)
                {
                    db.AbortTransaction();
                    json.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("TradeOrderNoExist"), info.TradeOrderNO);
                    return false;
                }
                sql = new Sql();
                //库存条码信息  只查询有实物的灯珠
                sql.Append(this.SqlSelect);
                if (!string.IsNullOrWhiteSpace(TradeSourceList.BatchNO))
                {
                    sql.Where($"BasBarcodeInfo.BatchNO='{TradeSourceList.BatchNO}'");
                }
                if (!string.IsNullOrWhiteSpace(TradeSourceList.StorageNO))
                {
                    sql.Where($"BasStorageInfo.StorageNO='{TradeSourceList.StorageNO}'");
                }
                else
                {
                    json.Message = ErrorCode.WarehouseInfo01.GetMessage(TradeSourceList.StorageNO);
                    return false;
                }
                if (info != null)
                {
                    sql.Where($"WmsStockBarcode.MaterialID = (SELECT MaterialID FROM BasMaterialInfo WHERE MaterialNO = '{info.MaterialNO}')");
                    sql.Where($"WmsStockBarcode.WarehouseID = '{info.FromWarehouseID}'");
                }
                if (!string.IsNullOrWhiteSpace(BarCodeNO))
                {
                    sql.Where($"BasBarcodeInfo.BarcodeNO='{BarCodeNO}'");
                }
                sql.Where("WmsStockBarcode.IsLock=0 And BasBarcodeInfo.IsStock=1");
                sql.OrderBy("BasBarcodeInfo.BatchNO ASC");
                sql.OrderBy("WmsStockBarcode.StockQty ASC");
                List<WmsStockBarcode> allBarcodes = myDataBase.Fetch<WmsStockBarcode>(sql);
                if (!allBarcodes.Any())
                {
                    json.Message = string.Format(SysMessageInfoBLL.GetMessageInfo("NoExistBaercode"), info != null ? info.TradeOrderNO : BarCodeNO);
                    return false;
                }
                string IDs = "";
                // 2. 累加数量，找出满足 info.Qty 的最小集合
                decimal? totalSelectedQty = 0;
                List<WmsStockBarcode> selectedBarcodes = new List<WmsStockBarcode>();
                if (!string.IsNullOrWhiteSpace(BarCodeNO))
                {
                    selectedBarcodes = allBarcodes;
                    IDs = "'" + allBarcodes[0].BarcodeID + "',";
                }
                else
                {
                    foreach (var barcode in allBarcodes)
                    {
                        IDs += "'" + barcode.BarcodeID + "',";
                        selectedBarcodes.Add(barcode);
                        totalSelectedQty += barcode.StockQty;
                        if (totalSelectedQty >= info.RequestQty)
                            break;
                    }
                }
                foreach (var item in selectedBarcodes)
                {
                    //添加单据条码明细
                    WmsTradebarcode tradebarcode = new WmsTradebarcode();
                    tradebarcode.TradebarcodeID = Guid.NewGuid().ToString();
                    tradebarcode.TradeOrderID = TradeSourceList.TradeOrderID;
                    tradebarcode.BarcodeID = item.BarcodeID;
                    tradebarcode.StorageID = item.StorageID;
                    tradebarcode.LampID = item.LampID;
                    tradebarcode.Qty = item.StockQty;
                    tradebarcode.LampCode = item.LampCode;
                    tradebarcode.LampNO = item.LampNO;
                    tradebarcode.StorageNO = item.StorageNO;
                    tradebarcode.BarcodeNO = item.BarcodeNO;
                    tradebarcode.TradeSourceID = TradeSourceList.TradeSourceID;
                    sb.Append(BusinessTool.GetInsertSql(tradebarcode));
                    json.Items.Add(tradebarcode);
                }
                //回写来源单据号
                TradeSourceList.CalculateQty += totalSelectedQty;
                sb.Append(BusinessTool.GetUpdateSql(TradeSourceList));
                IDs = IDs.Substring(0, IDs.Length - 1);
                sb.Append($"Update WmsStockBarcode Set IsLock=1 where WmsStockBarcode.BarcodeID in ({IDs})");

                if (sb.Length > 0)
                {
                    db.Execute(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                db.AbortTransaction();
                return false;
            }
            db.CompleteTransaction();
            return true;
        }
    }
}